﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Threading;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
namespace TaskSystemClient
{
    static class Program
    {

        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            //检查参数，看当前进程是否是更新程序
            string processName = Path.GetFileNameWithoutExtension(System.Diagnostics.Process.GetCurrentProcess().ProcessName);
            if (processName.ToUpper().Equals("SPM_UPDATE"))
            {
                StartUpdate();
            }
            else
            {
                //查找更新程序，若有则删掉
                RemoveFile("SPM_UPDATE.EXE");
                StartSPM(args);
            }
        }
        static void StartUpdate()
        {
            //首先检查文件，然后再删除SPM和GameEditor.Common.DLL
            /*
            if (!(File.Exists(@"\\192.168.40.201\共享\Update\SPM.EXE") && File.Exists(@"\\192.168.40.201\共享\Update\GameEditor.Common.DLL")))
            {
                MessageBox.Show("找不到更新程序的数据源，程序将自动关闭!", "更新SPM", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            try
            {
                //等待SPM进程结束，如果没结束则直接强制杀掉进程
                RemoveFile("SPM.EXE");
                RemoveFile("GameEditor.Common.dll");
            }
            catch (Exception)
            {
                MessageBox.Show("删除老文件失败，程序将自动关闭!", "更新SPM", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            try
            {
                File.Copy(@"\\192.168.40.114\共享\Update\SPM.EXE", "SPM.EXE");
                File.Copy(@"\\192.168.40.114\共享\Update\GameEditor.Common.DLL", "GameEditor.Common.DLL");
                MessageBox.Show("更新文件成功，点击确定启动新版本!", "更新SPM", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception)
            {
                MessageBox.Show("更新文件失败，程序将自动关闭!", "更新SPM", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            try
            {
                System.Diagnostics.Process.Start("spm.exe");
            }
            catch (Exception)
            {
                MessageBox.Show("启动新版本失败，程序将自动关闭!", "更新SPM", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            */
        }


        static void RemoveFile(string fileName)
        {
            string name = Path.GetFileNameWithoutExtension(fileName);
            System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName(name);
            if (processes.Length != 0)
            {
                foreach (System.Diagnostics.Process p in processes)
                {
                    if (p.HasExited)
                        continue;
                    if (!p.WaitForExit(500))
                    {
                        p.Kill();
                    }
                }
            }
            try
            {
                if (File.Exists(fileName))
                    File.Delete(fileName);
            }
            catch (Exception)
            {
                try
                {
                    System.Threading.Thread.Sleep(1000);
                    File.Delete(fileName);
                }
                catch (Exception)
                {

                }
            }
        }
        static void StartSPM(string[] args)
        {

            //{
            //    {
            //        string v1 = @"spm:///1932";
            //        ExternCommandHelper.ParseCommand(v1.Split(' '));
            //    }
            //    {
            //        string v1 = @"svn post-commit A.txt 3 B.txt 149 e:\work\work\trunk\code\client\";
            //        ExternCommandHelper.ParseCommand(v1.Split(' '));
            //    }
            //    { //error format1 缺目录
            //        string v1 = @"svn post-commit A.txt 3 B.txt 149";
            //        ExternCommandHelper.ParseCommand(v1.Split(' '));
            //    }
            //    { //error format2 不支持的事件 precommit
            //        string v1 = @"svn pre-commit A.txt 3 B.txt e:\work\work\trunk\code\client\";
            //        ExternCommandHelper.ParseCommand(v1.Split(' '));
            //    }
            //    { //error format2 不支持的主命令
            //        string v1 = @"other pre-commit A.txt 3 B.txt e:\work\work\trunk\code\client\";
            //        ExternCommandHelper.ParseCommand(v1.Split(' '));
            //    }
            //}

            if (!FileTypeRegister.UrlTypeRegistered("spm"))
            {
                UrlRegInfo uri = new UrlRegInfo();
                uri.ProtocolName = "spm";
                uri.ExePath = Application.ExecutablePath;
                uri.IcoPath = uri.ExePath + ",0";
                FileTypeRegister.RegisterUrlType(uri);

                GameEditor.Common.Dialogs.Warning("已经注册了URL协议 spm:// ", "SPM");
            }

            if (!FileTypeRegister.UrlTypeRegistered("spmsvn"))
            {
                UrlRegInfo uri = new UrlRegInfo();
                uri.ProtocolName = "spmsvn";
                uri.ExePath = Application.ExecutablePath;
                uri.IcoPath = uri.ExePath + ",0";
                FileTypeRegister.RegisterUrlType(uri);

                GameEditor.Common.Dialogs.Warning("已经注册了URL协议 spmsvn:// ", "SPM");
            }

            //PATH DEPTH MESSAGEFILE REVISION ERROR CWD 
            //GameEditor.Common.Dialogs.Warning(string.Join(" ", args), "命令行参数");
            Mutex mutex = new Mutex(false, "SPMClientMutex");
            if (!mutex.WaitOne(10, false))
            {
                IntPtr handler = Win32SDK.User32.FindWindow(null, @"SPM");
                if (handler != null)
                {
                    Win32SDK.User32.SetActiveWindow(new HandleRef(null, handler));
                }
                if (args.Length > 0)
                {
                    ExternCommandHelper.SendExternCommand(args);
                    return;
                }

                GameEditor.Common.Dialogs.Error("SPM已经启动了！", "SPM");
                return;
            }


            Application.SetCompatibleTextRenderingDefault(false);
            //启动通讯服务
            //LAN.CommunicationService.StartService();
            try
            {
                ExternCommandHelper.ParseCommand(args,false);
                MainForm mf = new MainForm();
                mf.Show();
                UIThread.Run(mf);
            }
            catch (System.Security.SecurityException)
            {
            }
            //catch (Exception e)
            //{
            //    //GameEditor.Common.Dialogs.ShowException(e);
            //    throw e;
            //}
            finally
            {
                mutex.ReleaseMutex();
            }
        }
    }

    public class FileTypeRegInfo
    {
        /// <Summary>
        /// 目标类型文件的扩展名
        /// </Summary>
        public string ExtendName ;  //".spm"
        
        /// <Summary>
        /// 目标文件类型说明
        /// </Summary>
        public string Description ; 

        /// <Summary>
        /// 目标类型文件关联的图标
        /// </Summary>
        public string IcoPath ;

        /// <Summary>
        /// 打开目标类型文件的应用程序
        /// </Summary>
        public string ExePath ;

        public FileTypeRegInfo()
        {
        }

        public FileTypeRegInfo(string ExtendName)
        {
            this.ExtendName = ExtendName ;
        }
    }

    public class UrlRegInfo
    {
        /// <Summary>
        /// 目标类型文件的扩展名
        /// </Summary>
        public string ProtocolName;  //"spm"

        /// <Summary>
        /// 目标类型文件关联的图标
        /// </Summary>
        public string IcoPath;

        /// <Summary>
        /// 打开目标类型文件的应用程序
        /// </Summary>
        public string ExePath;

        public UrlRegInfo()
        {
        }

        public UrlRegInfo(string protocolName)
        {
            this.ProtocolName = protocolName;
        }
    }

    /// <Summary>
    /// FileTypeRegister 用于注册自定义的文件类型。
    /// Zhuweisky 2005.08.31
    /// </Summary>
    public class FileTypeRegister
    {        
        #region RegisterFileType
        /// <Summary>
        /// RegisterFileType 使文件类型与对应的图标及应用程序关联起来。
        /// </Summary>        
        public static void RegisterFileType(FileTypeRegInfo RegInfo)
        {
            if(FileTypeRegistered(RegInfo.ExtendName))
            {
                return ;
            }

            string RelationName = RegInfo.ExtendName.Substring(1 ,RegInfo.ExtendName.Length-1).ToUpper() + "_FileType" ;

            RegistryKey FileTypeKey = Registry.ClassesRoot.CreateSubKey(RegInfo.ExtendName) ;
            FileTypeKey.SetValue("" ,RelationName) ;
            FileTypeKey.Close() ;
            
            RegistryKey RelationKey = Registry.ClassesRoot.CreateSubKey(RelationName) ;
            RelationKey.SetValue("" ,RegInfo.Description) ;

            RegistryKey IconKey = RelationKey.CreateSubKey("DefaultIcon") ;
            IconKey.SetValue("" ,RegInfo.IcoPath) ;

            RegistryKey ShellKey   = RelationKey.CreateSubKey("Shell") ;
            RegistryKey OpenKey    = ShellKey.CreateSubKey("Open") ;
            RegistryKey CommandKey = OpenKey.CreateSubKey("Command") ;
            CommandKey.SetValue("" ,RegInfo.ExePath + " %1") ;
            
            RelationKey.Close() ;
        }


        /// <Summary>
        /// RegisterFileType 使文件类型与对应的图标及应用程序关联起来。
        /// </Summary>        
        public static void RegisterUrlType(UrlRegInfo RegInfo)
        {
            if (FileTypeRegistered(RegInfo.ProtocolName))
            {
                return;
            }

            RegistryKey UrlTypeKey = Registry.ClassesRoot.CreateSubKey(RegInfo.ProtocolName);
            UrlTypeKey.SetValue("URL Protocol", "");
            UrlTypeKey.SetValue("", "URL:" + RegInfo.ProtocolName+" Protocol");

            RegistryKey IconKey = UrlTypeKey.CreateSubKey("DefaultIcon");
            IconKey.SetValue("", RegInfo.IcoPath);
            IconKey.Close();

            RegistryKey ShellKey = UrlTypeKey.CreateSubKey("Shell");
            RegistryKey OpenKey = ShellKey.CreateSubKey("Open");
            RegistryKey CommandKey = OpenKey.CreateSubKey("Command");
            CommandKey.SetValue("", RegInfo.ExePath + " %1");
            CommandKey.Close();
            OpenKey.Close();
            ShellKey.Close();

            UrlTypeKey.Close();
        }

        /// <Summary>
        /// FileTypeRegistered 指定文件类型是否已经注册
        /// </Summary>        
        public static bool UrlTypeRegistered(string ProtocolName)
        {
            RegistryKey SoftwareKey = Registry.ClassesRoot.OpenSubKey(ProtocolName);
            if (SoftwareKey != null)
            {
                return true;
            }

            return false;
        }


        /// <Summary>
        /// GetFileTypeRegInfo 得到指定文件类型关联信息
        /// </Summary>        
        public static FileTypeRegInfo GetFileTypeRegInfo(string ExtendName)
        {
            if(! FileTypeRegistered(ExtendName))
            {
                return null ;
            }

            FileTypeRegInfo RegInfo = new FileTypeRegInfo(ExtendName) ;

            string RelationName     = ExtendName.Substring(1 ,ExtendName.Length-1).ToUpper() + "_FileType" ;
            RegistryKey RelationKey = Registry.ClassesRoot.OpenSubKey(RelationName) ;
            RegInfo.Description = RelationKey.GetValue("").ToString();

            RegistryKey IconKey = RelationKey.OpenSubKey("DefaultIcon") ;
            RegInfo.IcoPath     = IconKey.GetValue("").ToString();

            RegistryKey ShellKey   = RelationKey.OpenSubKey("Shell") ;
            RegistryKey OpenKey    = ShellKey.OpenSubKey("Open") ;
            RegistryKey CommandKey = OpenKey.OpenSubKey("Command") ;
            string Temp = CommandKey.GetValue("").ToString();    
            RegInfo.ExePath           = Temp.Substring(0 ,Temp.Length-3) ;  
   
            return RegInfo ;
        }

        /// <Summary>
        /// GetFileTypeRegInfo 得到指定文件类型关联信息
        /// </Summary>        
        public static FileTypeRegInfo GetFileTypeRegInfo(string ExtendName,string RelationName)
        {
            if (!FileTypeRegistered(ExtendName))
            {
                return null;
            }

            FileTypeRegInfo RegInfo = new FileTypeRegInfo(ExtendName);

            RegistryKey RelationKey = Registry.ClassesRoot.OpenSubKey(RelationName);
            if (RelationKey == null)
            {
                return null;
            }
            RegInfo.Description = RelationKey.GetValue("").ToString();

            RegistryKey IconKey = RelationKey.OpenSubKey("DefaultIcon");
            RegInfo.IcoPath = IconKey.GetValue("").ToString();

            RegistryKey ShellKey = RelationKey.OpenSubKey("Shell");
            RegistryKey OpenKey = ShellKey.OpenSubKey("Open");
            RegistryKey CommandKey = OpenKey.OpenSubKey("Command");
            string Temp = CommandKey.GetValue("").ToString();
            RegInfo.ExePath = Temp.Substring(0, Temp.Length - 3);

            return RegInfo;
        }

        /// <Summary>
        /// UpdateFileTypeRegInfo 更新指定文件类型关联信息
        /// </Summary>    
        public static bool UpdateFileTypeRegInfo(FileTypeRegInfo RegInfo)
        {
            if(! FileTypeRegistered(RegInfo.ExtendName))
            {
                return false ;
            }   
            string ExtendName       = RegInfo.ExtendName ;
            string RelationName     = ExtendName.Substring(1 ,ExtendName.Length-1).ToUpper() + "_FileType" ;
            RegistryKey RelationKey = Registry.ClassesRoot.OpenSubKey(RelationName, true);
            RelationKey.SetValue("" ,RegInfo.Description) ;

            RegistryKey IconKey = RelationKey.OpenSubKey("DefaultIcon" ,true) ;
            IconKey.SetValue("" ,RegInfo.IcoPath);

            RegistryKey ShellKey   = RelationKey.OpenSubKey("Shell") ;
            RegistryKey OpenKey    = ShellKey.OpenSubKey("Open") ;
            RegistryKey CommandKey = OpenKey.OpenSubKey("Command", true);
            CommandKey.SetValue("" ,RegInfo.ExePath + " %1") ;   

            RelationKey.Close() ;
            return true;
        }

        /// <Summary>
        /// FileTypeRegistered 指定文件类型是否已经注册
        /// </Summary>        
        public static bool FileTypeRegistered(string ExtendName)
        {
            RegistryKey SoftwareKey = Registry.ClassesRoot.OpenSubKey(ExtendName);
            if(SoftwareKey != null)
            {
                return true ;
            }

            return false ;
        }
        #endregion
    }
}